import request from '@/utils/request'
import { ApiRes, RootObject, Suggestion } from '@/types/data'
import { RootThunkAction } from '@/types/store'
import { removeLocalHistories, setLocalHistories } from '@/utils/search'

// 获取搜索建议列表
export function getSuggestion(keyword: string): RootThunkAction {
  return async (dispatch) => {
    const q = keyword.trim()

    let suggestion: Suggestion = []

    // 关键字不为空才发送请求
    if (q) {
      const res = await request.get<
        ApiRes<{
          options: Suggestion
        }>
      >('/suggestion', {
        params: { q }
      })

      suggestion = res.data.data.options
    }

    dispatch({
      type: 'search/set_suggestion',
      payload: suggestion
    })
  }
}

// 添搜索历史记录
export function setSearchHistories(keyword: string): RootThunkAction {
  return async (dispatch, getState) => {
    let histories = getState().search.histories

    // 1.去重
    histories = histories.filter((item) => item !== keyword)

    // 2.添加keyword
    histories = [keyword, ...histories]

    // 3.限制最多显示条数
    if (histories.length > 10) {
      histories = histories.slice(0, 10)
    }

    // 保存到 Redux
    dispatch({
      type: 'search/set_history',
      payload: histories
    })

    // 保存到本地
    setLocalHistories(histories)
  }
}

// 清空搜索历史记录
export function clearHistory(): RootThunkAction {
  return async (dispatch) => {
    // 清空本地历史记录
    removeLocalHistories()

    // 清空redux数据
    dispatch({
      type: 'search/clear_history'
    })
  }
}

// 搜索详情
export function getSearchResults(
  keyword: string,
  page = 1,
  per_page = 10
): RootThunkAction {
  return async (dispatch) => {
    const res = await request.get<RootObject>('/search', {
      params: {
        q: keyword,
        page,
        per_page
      }
    })

    const articles = res.data.data.results

    dispatch({
      type: 'search/set_results',
      payload: articles
    })
  }
}
